﻿using Furion;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Text.Json;

namespace GSOrganization.Web.Core;

public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCorsAccessor();//启用跨域

        services.AddConsoleFormatter();//控制台日志输出

        //JWT 和 Cookies 混合身份验证
        services.AddJwt<JwtHandler>(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
        {
            options.LoginPath = "/Login";
        });

        /*报错信息：“System.Text.Json.JsonException: A possible object cycle was detected. 
         * This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
         * Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path:
         *  
**问题描述：**这个错误是由于 JSON 序列化时出现了循环引用（也就是对象之间相互引用）导致的。
*默认情况下，EF Core 的导航属性是延迟加载的，
*这就意味着当你序列化实体类时，会包含很多导航属性，
*这些导航属性中可能会有循环引用，从而导致上面的错误。
————————————————
*/
        services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
    });




        services.AddControllersWithViews()
            .AddInjectWithUnifyResult<StandardRestfulResultProvider>()//格式化api，给api包裹一层外衣
            .AddInjectBase().AddJsonOptions(item =>
            {
                item.JsonSerializerOptions.Converters.AddDateTimeTypeConverters("yyyy-MM-dd");
                item.JsonSerializerOptions.PropertyNamingPolicy = null; //json保持属性名称不变
            });

        services.AddControllersWithViews(x => x.SuppressAsyncSuffixInActionNames = false);
        //.AddRazorRuntimeCompilation();<!--view文件夹下的内容不编译-->
        services.AddSession();
        //services.AddRemoteRequest();
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseHttpsRedirection().UseCors(builder =>
            builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            //app.UseHsts();
        }

        app.UseCorsAccessor();//启用跨域
        //项目去掉https的方法如下：
        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseInjectBase();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Login}/{action=Index}/{id?}"); //登录页作为起始页
        });
    }
}